import { isObj ,isArr } from '../utils.js'


export class VNode {
    constructor(tag, attrs, children){
        this.tag = tag;
        this.attrs = attrs;
        this.children = children ?
                        isArr(children) ?
                        children :
                        [children] :
                        [];
    }
}

export function createEmptyVnode(){
    return null;
}

export function createElement(tag, attrs, children){
    return new VNode(tag, attrs, children)
}

function setAttrs(ele, attr, value){

    switch(attr){
        case ele.tagName === 'INPUT' || ele.tagName === 'TEXTAREA':
            ele.value = value;
            break;
        case 'style':
            if(typeof value === 'string'){
                ele.style.cssText = value;
            }else if(typeof value === 'object'){
                for(let i in value){
                    ele.style[i] = value[i];
                }
            }
            break;
        default:
            ele.setAttribute(attr, value);
            break;
    }
}

function renderVnodeChildren( ele, vnodeChildren){

    vnodeChildren.forEach(c => {
        if(c instanceof VNode){
            ele.appendChild(renderRealDomByVnode(c));
        }else if(typeof c === 'string'){
            ele.appendChild(document.createTextNode(c));
        }
    });
}


export function renderRealDomByVnode(vnode){
    var doc;
    if(vnode.tag) {
        doc = document.createElement(vnode.tag);
        if(vnode.attrs && isObj(vnode.attrs)){
            for(let attr in vnode.attrs){
                setAttrs(doc, attr, vnode.attrs[attr]);
            }
        }

        if(Array.isArray(vnode.children) && vnode.children.length > 0) {

            renderVnodeChildren(doc, vnode.children)
        }
    }else{
        doc = document.createTextNode(vnode.children);
    }

    return doc;
}

export function render(rootEle, renderEle){
    rootEle.appendChild(renderEle);
}

export function renderDOM(rootEle, renderEle){
    rootEle.appendChild(renderEle);
}
